<template>
	<view class="main">
		<view class="content">
			<image class="logo" src="../../static/logo.png" mode=""></image>
			<view class="title">人民放映</view>
			<view class="des">您尚未登录</view>
			<view class="des">需要获取您的授权后进入</view>
			<view class="wx">
				<view class="no_login" @click="ToPage">暂不登录</view>
				<!-- #ifdef H5 -->
				<button type="primary" class="page-body-button" @click="Topages('/Login/TelLogin')">账户登录</button>
				<!-- #endif -->
				<!-- #ifdef APP-PLUS -->
				<!-- <button type="primary" class="page-body-button" @click="tologin('weixin')">微信登录</button> -->
				<button type="success" v-if="wx_login" :loading="loading" class="page-body-button"
					@click="tologin()">微信登录</button>

				<!-- #endif -->
				<!-- #ifdef MP-WEIXIN -->
				<u-button :loading="loading" shape="circle" type="success" open-type="getUserInfo" @getuserinfo="login">
					微信登录</u-button>
				<!-- #endif -->

				<!-- 苹果登录 -->
				<image src="../../static/1.png" @click="appleLogin" v-if="showApple" class="apple-btn" mode=""></image>


			</view>
			<!-- #ifdef APP-PLUS -->
			<view class="tel">
				<u-button shape="circle" type="error" v-if="!wx_login" @click="Topages('/Login/TelLogin')">登录</u-button>
			</view>
			<view class="tel">
				<u-button shape="circle" type="error" v-if="!wx_login" @click="Topages('/Login/register')">注册</u-button>
			</view>
			<!-- #endif -->
			<view class="text">
				<u-checkbox v-model="init">我已阅读并同意</u-checkbox> <text @click="Todial()">《人民放映隐私政策》</text>
			</view>

		</view>
		<u-top-tips ref="uTips"></u-top-tips>

		<u-modal v-model="show" :show-confirm-button='false'>
			<view class="slot-content">
				<view class="con">
					为了给您带来更好的体验我们将获取您的手机号
				</view>
				<view class="btns">
					<view class="item">
						<u-button type="info" size='medium' @click="close">取消</u-button>
					</view>
					<view class="item">
						<u-button type="primary" size='medium' open-type="getPhoneNumber" @getphonenumber="getPhone">授权
						</u-button>
					</view>
				</view>
			</view>
		</u-modal>
		<u-toast ref="uToast" />
	</view>

</template>

<script>
	export default {

		data() {
			return {

				loading: false,
				InvitedCode: '', //邀请码
				userInfo: {},
				loginData: {},
				PrevUrl: '',
				actId: '', // 活动订单
				Buy_tickets: {},
				show: false,
				phone: '',
				init: false,
				wx_login: false, //是否显示微信登录
				showApple: true,
			}
		},
		onLoad(e) {
			try {
				// 先判断 系统版本
				var that = this;
				uni.getSystemInfo({
					success: function(res) {
						that.system = Number(res.system.substring(4, 6))
						that.platform = res.platform
						let panduan = that.platform == 'ios' && that.system >= 13
						if (that.platform == 'ios' && that.system < 13) {
							//不支持苹果登录
							this.showApple = false;
						} else if (that.platform == 'ios' && that.system >= 13) {
							//调用苹果登录
							that.showApple = true;
						}
					}
				});


				const value = uni.getStorageSync('InvitedCode');
				const Buy_tickets = uni.getStorageSync('Buy_tickets')
				const PrevUrl = uni.getStorageSync('PrevUrl')
				const actId = uni.getStorageSync('actId')
				// console.log('获取到的活动路径-----', actId)

				const wx_login = uni.getStorageSync('isLoginShow')
				console.log('获取到的邀请码-----', value)
				console.log('是否显示微信登录-----', wx_login)
				console.log('获取到的Buy_tickets-----', Buy_tickets)
				console.log('获取到的上级url-----', PrevUrl)

				this.Buy_tickets = Buy_tickets
				if (PrevUrl) {
					this.PrevUrl = PrevUrl
				}

				if (actId) {
					this.actId = actId
				}

				if (wx_login) {
					this.wx_login = wx_login
				}
				if (value) {
					this.InvitedCode = value
				} else {
					this.InvitedCode = e.userId || e.InvitedCode
					console.log('获取到的邀请码-----', this.InvitedCode)
				}
			} catch (e) {
				// error
			}

			// uni.getProvider({
			// 	service: 'oauth',
			// 	success: (result) => {
			// 		console.log('获取登录通道成功---------------------',result)
			// 	},
			// 	fail: (error) => {
			// 		console.log('获取登录通道失败', error);
			// 	}
			// });
		},

		onShow() {
			this.losd()
			try {
				const userInfo = uni.getStorageSync('userInfo');
				console.log('当前用户信息---------------------------', userInfo)
				if (userInfo) {
					this.phone = userInfo.phone
				}
			} catch (e) {
				// error
			}
		},
		onPullDownRefresh() {
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		methods: {

			// 苹果登录
			appleLogin() {
				if (!this.init) {
					this.$refs.uToast.show({
						title: '请勾选相关协议',
						type: 'error',
					})
					return
				}

				

				// 苹果登录
				uni.login({
					provider: 'apple',
					success: (loginRes) => {
						uni.getUserInfo({
							provider: 'apple',
							success: (res) => {
								let appleid = res.userInfo.openId;
								uni.removeStorage( {key: 'userInfo'});
								uni.setStorageSync('appleid', appleid);
								console.log(res,uni.getStorageSync('appleid'));
								uni.switchTab({
									url: '/pages/Chartered/index'
								});
								/*
								返回的数据
								{
									"errMsg": "getUserInfo:ok",
									"rawData": "json字符串",
									"userInfo": {
										"openId": "xxx.xxxxx.xxx", // 苹果用户唯一标识符，该值在同一个开发者账号下的所有 App 下是一样的，开发者可以用该唯一标识符与自己后台系统的账号体系绑定起来。
										"fullName": {}, // 当且仅当第一次授权才会返回
										"authorizationCode": "12345678xxx", // 服务器验证需要使用的参数
										"identityToken": "header.payload.signature", // 服务器验证需要使用的参数
										"realUserStatus": 1 // 用于判断当前登录的苹果账号是否是一个真实用户
									},
									"signature": ""
								}
								*/
							}
						})
					},
					fail: (err) => {
						this.$refs.uTips.show({
							title: '登录失败',
							type: 'error',
							duration: '2300'
						})
					}
				})
			},


			ToPage() {
				uni.removeStorageSync('token')
				uni.removeStorageSync('actId');
				uni.removeStorageSync('appleid');
				if (this.actId) {
					uni.redirectTo({
						url: this.actId
					});
					uni.removeStorageSync('actId')
				} else {
					uni.switchTab({
						url: '/pages/Chartered/index'
					});
				}
			},
			Todial() {
				uni.navigateTo({
					url: '/pages/Content/Detail?type=3&id=12'
				})
			},
			tologin() {
				if (!this.init) {
					this.$refs.uToast.show({
						title: '请勾选相关协议',
						type: 'error',
					})
					return
				}
				uni.login({
					provider: 'weixin',
					success: (res) => {
						console.log('login success:', res);
						uni.setStorage({
							key: 'openId',
							data: res.authResult.openid,
						});
						this.appLogin(res.authResult)
						// this.Toast({
						// 	title: '登录成功'
						// })

					},
					fail: (err) => {
						console.log('login fail:', err);

						// 一键登录点击其他登录方式
						if (err.code == '30002') {
							uni.closeAuthView();
							this.Toast({
								title: '其他登录方式'
							})
							return;
						}

						// 未开通
						if (err.code == 1000) {
							uni.showModal({
								title: '登录失败',
								content: `${err.errMsg}\n，错误码：${err.code}`,
								confirmText: '开通指南',
								cancelText: '确定',
								success: (res) => {
									if (res.confirm) {
										setTimeout(() => {
											plus.runtime.openWeb(
												'https://ask.dcloud.net.cn/article/37965'
											)
										}, 500)
									}
								}
							});
							return;
						}

						// 一键登录预登陆失败
						// if (err.code == '30005') {
						// 	uni.showModal({
						// 		showCancel: false,
						// 		title: '预登录失败',
						// 		content: this.univerifyErrorMsg || err.errMsg
						// 	});
						// 	return;
						// }

						// 一键登录用户关闭验证界面
						// if (err.code != '30003') {
						// 	uni.showModal({
						// 		showCancel: false,
						// 		title: '登录失败',
						// 		content: JSON.stringify(err)
						// 	});
						// }
					},
					complete: () => {
						this.univerifyBtnLoading = false;
					}
				});
			},
			//App登录
			losd() {
				this.$http({
					url: this.$api.getSettingDetail,
					method: 'GET',
					hideLoading: true,
					data: {
						id: 11
					},
					success: res => {
						if (res.data.info == 1) {
							this.wx_login = true
						} else {
							this.wx_login = false
						}
					}
				})

			},
			appLogin(e) {
				if (!this.init) {
					this.$refs.uToast.show({
						title: '请勾选相关协议',
						type: 'error',
					})
					return
				}
				this.loading = true
				this.$http({
					url: this.$api.getUserInfo,
					method: 'POST',
					hideLoading: true,
					data: e,
					success: res => {
						console.log(res);
						if (res.data.id && !res.data.phone) {
							uni.setStorageSync('token', res.data.token)
							this.gopage(res.data.id)
						} else {
							console.log('登录结果----------', res)
							uni.setStorageSync('token', res.data.token)
							this.uniapppush(res)
							uni.setStorage({
								key: 'userInfo',
								data: res.data,
								success: ress => {
									console.log('success', ress);
									if (this.PrevUrl == 'pages/SessionDetail/index') {
										uni.reLaunch({
											url: `/${this.PrevUrl}?dyId=${this.Buy_tickets.dyId}&userId=${this.Buy_tickets.userId}`
										});
									}
									console.log(this.actId)
									if (this.actId) {
										uni.redirectTo({
											url: this.actId
										});
										uni.switchTab({
											url: this.actId
										});
										uni.removeStorageSync('actId')

									} else {
										uni.switchTab({
											url: '/pages/Chartered/index'
										});
									}

								}
							});
					
						}


					},
					complete: e => {
						this.loading = false
					}
				})
			},
			uniapppush(res) {
				const clientInfo = plus.push.getClientInfo()
				if (clientInfo.clientid == null) {} else {
					this.$http({
						url: this.$api.updateClientId,
						method: 'POST',
						hideLoading: true,
						data: {
							id: res.data.id,
							clientId: clientInfo.clientid
						},
						success: res => {
							console.log('设备编码----------', res)
						},
					})
				}
			},
			//绑定手机号
			gopage(id) {
				uni.navigateTo({
					url: '/pages/PersonalInfo/bding?id=' + id
				})
			},
			topage1(id) {
				uni.navigateTo({
					url: '/pages/PersonalInfo/bding?appleToken=' + id
				})
			},


			// 小程序登录
			login(e) {
				if (!this.init) {
					this.$refs.uToast.show({
						title: '请勾选相关协议',
						type: 'error',
					})
					return
				}
				console.log(e)
				const _this = this
				if (e.detail.userInfo) {
					uni.login({
						provider: 'weixin',
						success: loginRes => {
							console.log('userInfo------', e.detail.userInfo)
							this.userInfo = e.detail.userInfo
							console.log('login--------', loginRes);
							this._login(loginRes.code)
						}
					});
				} else {
					this.$refs.uTips.show({
						title: '未授权，登录失败',
						type: 'error',
						duration: '2300'
					})
				}

			},
			_login(e) {
				this.loading = true
				this.$http({
					url: this.$api.WxLogin,
					method: 'GET',
					hideLoading: true,
					data: {
						code: e,
						InvitedCode: this.InvitedCode,
					},
					success: res => {
						console.log('登录结果----------', res)

						this.loginData = res.data
						if (!res.data.phone) {
							this.show = true
						} else {
							this._userinfo(res.data)
						}
						uni.setStorage({
							key: 'openId',
							data: res.data,
						});
					},
					complete: e => {
						this.loading = false
					}
				})
			},
			// 获取用户手机号
			getPhone(e) {
				e.detail.sessionKey = this.loginData.session_key
				console.log('用户手机号----------------------', e)
				this.$http({
					url: this.$api.WxGetUserInfo,
					method: 'GET',
					hideLoading: true,
					data: e.detail,
					success: res => {
						console.log('获取手机号成功--------------', res)
						this.userInfo.phone = res.data.phoneNumber

						this._userinfo(this.loginData)
					},
					fail: err => {
						console.log('获取手机号失败--------------', err)
						uni.showToast({
							title: '登录失败，手机号获取失败',
							duration: 2000,
							icon: 'none'
						});
					}
				})
			},
			//关闭手机号授权
			close() {
				this.show = false
				this._userinfo(this.loginData)
			},

			// 绑定用户信息
			_userinfo(e) {
				this.userInfo.openid = e.openid
				this.userInfo.unionid = e.unionid
				this.$http({
					url: this.$api.bindWxUser,
					method: 'POST',
					hideLoading: true,
					data: {
						InvitedCode: this.InvitedCode,
						avatarUrl: this.userInfo.avatarUrl,
						city: '',
						country: '',
						sex: this.userInfo.gender,
						nickname: this.userInfo.nickName,
						province: '',
						phone: this.userInfo.phone,
						openid: this.userInfo.openid,
						unionid: this.userInfo.unionid
					},
					success: res => {
						console.log('登录结果----------', res)
						if (res.code == 200) {
							uni.setStorageSync('token', res.data.token)
							uni.setStorage({
								key: 'userInfo',
								data: res.data,
								success: res => {
									if (this.actId) {
										uni.redirectTo({
											url: this.actId
										});
										uni.switchTab({
											url: this.actId
										});
										uni.removeStorageSync('actId')

									} else if (this.PrevUrl) {
										if (this.PrevUrl == 'pages/SessionDetail/index') {
											uni.reLaunch({
												url: `/${this.PrevUrl}?dyId=${this.Buy_tickets.dyId}&userId=${this.Buy_tickets.userId}`
											});
										} else {
											uni.switchTab({
												url: '/pages/Chartered/index'
											});
										}

									} else {

										uni.switchTab({
											url: '/pages/Chartered/index'
										});
									}

								}
							});
						}
					},
					fail: err => {

					},
					complete: e => {
						this.loading = false
					}
				})
			},
			Topages(e) {
				if (!this.init) {
					this.$refs.uToast.show({
						title: '请勾选相关协议',
						type: 'error',
					})
					return
				}
				uni.navigateTo({
					url: `/pages${e}`
				});
			},
		}
	}
</script>

<style lang="less" scoped>
	.main {
		display: flex;
		justify-content: center;
		min-height: 100vh;

		.content {
			width: 670rpx;
			text-align: center;
			padding-top: 140rpx;

			.logo {
				width: 174rpx;
				height: 174rpx;
			}

			.title {
				font-size: 36rpx;
				font-weight: 600;
				color: #333333;
				line-height: 50rpx;
			}

			.text text {
				color: #007AFF;
			}

			.des {
				font-size: 26rpx;
				font-weight: 400;
				color: #999999;
				line-height: 36rpx;
			}

			.no_login {
				width: 670rpx;
				height: 90rpx;
				background: #CBCCCD;
				border-radius: 45rpx;
				text-align: center;
				line-height: 90rpx;
				font-size: 36rpx;
				font-weight: 600;
				color: #FBFBFB;
				margin-bottom: 32rpx;
			}

			/deep/button {
				width: 670rpx;
				height: 90rpx;
				background: #09BB07;
				border-radius: 45rpx;
				font-size: 36rpx;
				font-weight: 600;
				color: #FBFBFB;
				line-height: 90rpx;
			}

			.wx {
				padding: 30rpx 0;
				// /deep/button{
				// 	background: #09BB07 url(../../static/icon/lwx.png)225rpx center no-repeat;
				// 	background-size: 40rpx 40rpx;
				// 	color: #FBFBFB;
				// }
			}

			.tel {
				padding: 30rpx 0;

				/deep/button {
					background: #ffffff;
					border-radius: 45rpx;
					border: 2rpx solid #EBEAEA;
					color: #333333;
				}
			}
		}

		.slot-content {
			padding: 30rpx;

			.con {
				font-size: 24rpx;
				line-height: 34rpx;
				text-align: center;
			}

			.btns {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: 30rpx;
				width: 100%;

				.item {
					/deep/.u-hairline-border:after {
						border: 0;
					}
				}
			}
		}
	}

	.apple-btn {
		width: 670rpx;
		height: 90rpx;
		background: url('@/static/apple.png') !important;
		background-size: 670rpx 90rpx !important;
		color: #fff;
		margin-top: 40rpx;
		border-radius: 40rpx;
	}
</style>
